package com.yunyouyi.cpicture.infrastructure.manager.upload;

import cn.hutool.core.io.FileUtil;
import com.yunyouyi.cpicture.infrastructure.exception.ErrorCode;
import com.yunyouyi.cpicture.infrastructure.exception.ThrowUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.List;

@Slf4j
@Service
public class FilePictureUpload extends PictureUploadTemplet {
    @Override
    protected void processFile(Object inputSource, File file) {
        MultipartFile multipartFile = (MultipartFile)inputSource;
        try {
            multipartFile.transferTo(file);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    protected String getOriginFilename(Object inputSource) {
        MultipartFile multipartFile = (MultipartFile)inputSource;
        return multipartFile.getOriginalFilename();
    }

    @Override
    protected void validPicture(Object inputSource) {
        MultipartFile multipartFile = (MultipartFile) inputSource;
        //限制文件大小
        long fileSize = multipartFile.getSize();
        ThrowUtils.throwIf(fileSize > 1024 * 1024 * 4, ErrorCode.PARAMS_ERROR,"文件大小不能超过4M");
        //判断后缀
        List<String> allowSuffixList = List.of("jpg", "jpeg", "png", "gif");
        String fileSuffix = FileUtil.getSuffix(multipartFile.getOriginalFilename());
        log.info("文件后缀{}",fileSuffix);
        ThrowUtils.throwIf(!allowSuffixList.contains(fileSuffix),ErrorCode.PARAMS_ERROR,"格式不支持");
    }
}
